﻿using System.Data;
using System.Reflection;

namespace Common;

public class DataTableHelper<T> where T : class
{
    /// <summary>  
    /// 用DataTable转换实体类
    /// </summary>  
    public static List<T> DataTableConvertToModel(DataTable dt)
    {
        if (dt == null || dt.Rows.Count == 0)
        {
            return null;
        }
        List<T> modelList = new List<T>();
        foreach (DataRow dr in dt.Rows)
        {
            T model = (T)Activator.CreateInstance(typeof(T));
            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
                if (propertyInfo != null && dr[i] != DBNull.Value)
                    propertyInfo.SetValue(model, Convert.ChangeType(dr[i], propertyInfo.PropertyType), null);
            }
            modelList.Add(model);
        }
        return modelList;
    }
}
